package com.toman.ui.report;


import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.xclcharts.chart.ArcLineChart;
import com.demo.xclcharts.view.ArcLineChart01View;
import com.demo.xclcharts.view.PieChart01View;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.CompanyBeltlineReportDto;
import com.toman.JavaBean.CompanyStaticsDataDto;
import com.toman.JavaBean.DeviceHouseDayPlanEntity;
import com.toman.JavaBean.DeviceHouseDayPlanMappingEntity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.NetworkUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.widget.CustomProgressBar;
import com.umeng.analytics.MobclickAgent;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.xclcharts.chart.ArcLineData;
import org.xclcharts.chart.PieData;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import lib.kingja.switchbutton.SwitchMultiButton;
import me.itangqi.waveloadingview.WaveLoadingView;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ReportFragment extends Fragment {
    CompanyBeltlineReportDto reportDto;
    String token, companyId, departmentId;
    Unbinder unbinder;
    CommonAdapter<DeviceHouseDayPlanMappingEntity> adapterEasy;
    List<DeviceHouseDayPlanMappingEntity> listEasy = new ArrayList<>();

    View rootView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_title_base)
    LinearLayout llTitleBase;
    @BindView(R.id.tv_easy_title)
    TextView tvEasyTitle;
    @BindView(R.id.iv_warn_easy)
    ImageView ivWarnEasy;
    @BindView(R.id.ll_easy)
    LinearLayout llEasy;
    @BindView(R.id.pb_easy)
    CustomProgressBar pbEasy;
    @BindView(R.id.tv_easy_rank)
    TextView tvEasyRank;
    @BindView(R.id.cv_easy)
    CardView cvEasy;
    @BindView(R.id.alc_device)
    ArcLineChart01View alcDevice;
    @BindView(R.id.ll_status)
    LinearLayout llStatus;
    @BindView(R.id.tv_device_rate_title)
    TextView tvDeviceRateTitle;
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    @BindView(R.id.line_device_rate)
    View lineDeviceRate;
    @BindView(R.id.sw_device_rate)
    SwitchMultiButton swDeviceRate;
    @BindView(R.id.ll_warn_device_rate)
    LinearLayout llWarnDeviceRate;
    @BindView(R.id.tv_device_tally_title)
    TextView tvDeviceTallyTitle;
    @BindView(R.id.line_device_tally)
    View lineDeviceTally;
    @BindView(R.id.pc_tally)
    PieChart01View pcTally;
    @BindView(R.id.tv_output_month_this)
    TextView tvOutputMonthThis;
    @BindView(R.id.tv_output_month_last)
    TextView tvOutputMonthLast;
    @BindView(R.id.tv_output_day_this)
    TextView tvOutputDayThis;
    @BindView(R.id.tv_output_day_last)
    TextView tvOutputDayLast;
    @BindView(R.id.tv_easy_rate)
    TextView tvEasyRate;
    @BindView(R.id.tv_easy_plan)
    TextView tvEasyPlan;
    @BindView(R.id.tv_easy_report)
    TextView tvEasyReport;
    @BindView(R.id.tv_easy_collect)
    TextView tvEasyCollect;
    @BindView(R.id.rv_easy)
    RecyclerView rvEasy;
    @BindView(R.id.tv_plan_title)
    TextView tvPlanTitle;
    @BindView(R.id.line_plan)
    View linePlan;
    @BindView(R.id.iv_warn_plan)
    ImageView ivWarnPlan;
    @BindView(R.id.ll_plan)
    LinearLayout llPlan;
    @BindView(R.id.pb_plan)
    CustomProgressBar pbPlan;
    @BindView(R.id.tv_plan_rank)
    TextView tvPlanRank;
    @BindView(R.id.tv_repair_title)
    TextView tvRepairTitle;
    @BindView(R.id.line_repair)
    View lineRepair;
    @BindView(R.id.tv_repair_subtitle1)
    TextView tvRepairSubtitle1;
    @BindView(R.id.tv_repair_subtitle2)
    TextView tvRepairSubtitle2;
    @BindView(R.id.tv_device_run_rate)
    TextView tvDeviceRunRate;
    @BindView(R.id.tv_device_freeturn_rate)
    TextView tvDeviceFreeturnRate;
    @BindView(R.id.tv_device_standby_rate)
    TextView tvDeviceStandbyRate;
    @BindView(R.id.tv_device_off_rate)
    TextView tvDeviceOffRate;
    @BindView(R.id.tv_device_run_count)
    TextView tvDeviceRunCount;
    @BindView(R.id.tv_device_freeturn_count)
    TextView tvDeviceFreeturnCount;
    @BindView(R.id.tv_device_standby_count)
    TextView tvDeviceStandbyCount;
    @BindView(R.id.tv_device_off_count)
    TextView tvDeviceOffCount;
    @BindView(R.id.tv_device_count)
    TextView tvDeviceCount;
    @BindView(R.id.wv_oee_now)
    WaveLoadingView wvOeeNow;
    @BindView(R.id.tv_oee_now)
    TextView tvOeeNow;
    @BindView(R.id.wv_oee_average)
    WaveLoadingView wvOeeAverage;
    @BindView(R.id.tv_oee_average)
    TextView tvOeeAverage;
    @BindView(R.id.wv_oee_top)
    WaveLoadingView wvOeeTop;
    @BindView(R.id.tv_oee_top)
    TextView tvOeeTop;
    @BindView(R.id.tv_repair_count)
    TextView tvRepairCount;
    @BindView(R.id.tv_check_count)
    TextView tvCheckCount;
    @BindView(R.id.tv_plan_rate)
    TextView tvPlanRate;
    @BindView(R.id.tv_plan_plan)
    TextView tvPlanPlan;
    @BindView(R.id.tv_plan_report)
    TextView tvPlanReport;
    @BindView(R.id.tv_plan_collect)
    TextView tvPlanCollect;
    @BindView(R.id.line_report_easy)
    View lineReportEasy;
    @BindView(R.id.rl_easy_rank)
    RelativeLayout rlEasyRank;


    public ReportFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_report,
                null);
        ButterKnife.bind(this, rootView);
        initView();
//        getData();

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.i("setDeviceConut", "AFragment-->onCreateView");
        ViewGroup perentView = (ViewGroup) rootView.getParent();
        if (perentView != null) {
            perentView.removeAllViewsInLayout();
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;

    }

    private void initView() {
        initAdapter();

        token = (String) SPUtils.get(getActivity(), "token", "");
        companyId = (String) SPUtils.get(getActivity(), "cpy_id", "");
        departmentId = (String) SPUtils.get(getActivity(), "departmentId", "");
        swDeviceRate.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
//                Toast.makeText(getActivity(), tabText, Toast.LENGTH_SHORT).show();
                setOee(reportDto);
            }

        });


//        setDeviceConut();


        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getActivity())) {
                    // 如果网络可用，则加载网络数据
                    getData();

                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });


    }

    private void initAdapter() {

        adapterEasy = new CommonAdapter<DeviceHouseDayPlanMappingEntity>(getActivity(), R.layout.item_report_easy, listEasy) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseDayPlanMappingEntity item, final int position) {
                TextView tv_num = holder.getView(R.id.tv_num);
                int num = position + 1;
                tv_num.setText(num + "");
                holder.setText(R.id.tv_belt, item.getBeltlineName());
                holder.setText(R.id.tv_rate, item.getCompleteRate());
                if (0 <= position && position <= 2) {
                    tv_num.setTextColor(Color.WHITE);
                    tv_num.setBackgroundResource(R.mipmap.report_icon_front);
                    holder.getView(R.id.iv_caution).setVisibility(View.GONE);

                    if (position == 2 & listEasy.size() > 3) {
                        holder.getView(R.id.tv_omit).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.tv_omit).setVisibility(View.GONE);
                    }
                } else {
                    tv_num.setTextColor(getResources().getColor(R.color.black66));
                    tv_num.setBackgroundResource(R.drawable.circle_report_gray);
                    holder.getView(R.id.iv_caution).setVisibility(View.VISIBLE);
                }

            }
        };
        rvEasy.setLayoutManager(new LinearLayoutManager(getActivity()));

        rvEasy.setAdapter(adapterEasy);
    }

    private void setDeviceConut(CompanyBeltlineReportDto bean
    ) {

        ArcLineChart chart = alcDevice.getChart();
//        chart.getPlotAttrInfo().addAttributeInfo(XEnum.Location.TOP, bean.getBeltlineCount() + "", 0.1f, alcDevice.getTitlePaint());
//        chart.getPlotAttrInfo().addAttributeInfo(XEnum.Location.BOTTOM, "设备总数", 0.1f, alcDevice.getSubPaint());
        LinkedList<ArcLineData> chartData = new LinkedList<ArcLineData>();
        double runPercent = 0, freeturnPercent = 0, StandbyPercent = 0, offPercent = 0;
        if (bean.getBeltlineCount() != 0) {
            runPercent = ((double) bean.getBeltlineAutorunCount() / (double) bean.getBeltlineCount()) * 100;
            freeturnPercent = ((double) bean.getBeltlineFreeturnCount() / (double) bean.getBeltlineCount()) * 100;
            StandbyPercent = ((double) bean.getBeltlineStandbyCount() / bean.getBeltlineCount()) * 100;
            offPercent = ((double) bean.getBeltlineOffCount() / bean.getBeltlineCount()) * 100;
            runPercent = (double) Math.round(runPercent * 100) / 100;
            freeturnPercent = (double) Math.round(freeturnPercent * 100) / 100;
            StandbyPercent = (double) Math.round(StandbyPercent * 100) / 100;
            offPercent = (double) Math.round(offPercent * 100) / 100;
        }
        chartData.add(new ArcLineData("closed", "29% - closed", runPercent, Color.rgb(88, 188, 73)));
        chartData.add(new ArcLineData("inspect", "53% - inspect", freeturnPercent, Color.rgb(80, 127, 216)));
        chartData.add(new ArcLineData("open", "76%", StandbyPercent, Color.rgb(246, 198, 0)));
        chartData.add(new ArcLineData("workdone", "86%", offPercent, Color.rgb(116, 116, 116)));
        alcDevice.chartDataSet(chartData);
        Object[] str = new Object[]{runPercent + "%", freeturnPercent + "%", StandbyPercent + "%", offPercent + "%", bean.getBeltlineAutorunCount() + "台",
                bean.getBeltlineFreeturnCount() + "台", bean.getBeltlineStandbyCount() + "台", bean.getBeltlineOffCount() + "台", bean.getBeltlineCount()};
        ViewUtil.setText(str, tvDeviceRunRate, tvDeviceFreeturnRate, tvDeviceStandbyRate, tvDeviceOffRate, tvDeviceRunCount, tvDeviceFreeturnCount,
                tvDeviceStandbyCount, tvDeviceOffCount, tvDeviceCount);

    }

    private void getData() {
        try {
            getFirst();
            getEasy();
            getTally();
            getPlan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getFirst() {
        OkHttpUtils
                .get(NewBaseUrl.getCompanyBDTCount)
                .headers("token", token)
                .params("companyId", companyId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("setDeviceConut", "获取首页汇总数据: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            CompanyBeltlineReportDto bean = (CompanyBeltlineReportDto) JSON.parseObject(jsonObj.getString("data"), CompanyBeltlineReportDto.class);
                            reportDto = bean;
                            Object[] str = new Object[]{bean.getMonthOutput(), "上月 " + bean.getLastMonthOutput(), bean.getTodayOutput(), "昨日 " + bean.getLastDayOutput()};
                            ViewUtil.setText(str, tvOutputMonthThis, tvOutputMonthLast, tvOutputDayThis, tvOutputDayLast);
                            setDeviceConut(bean);
                            setOee(bean);
                        } else {
                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }
                        bgaRefresh.endRefreshing();

                    }
                });
    }

    private void getEasy() {
        OkHttpUtils
                .get(NewBaseUrl.get_easy_report)
                .headers("token", token)
                .params("day", TimeUtil.getNowTimeNew())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("setDeviceConut", "获取简易车间汇总数据: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            if (StringUtils.isNotEmpty(jsonObj.getString("entity"))) {
                                DeviceHouseDayPlanEntity bean = (DeviceHouseDayPlanEntity) JSON.parseObject(jsonObj.getString("entity"), DeviceHouseDayPlanEntity.class);
                                Object[] str = new Object[]{bean.getCompleteRate() + "%", bean.getPlanOutput(), bean.getFinishCount(), bean.getReportOutput()};
                                ViewUtil.setText(str, tvEasyRate, tvEasyPlan, tvEasyReport, tvEasyCollect);
                                pbEasy.setCurProgress(Integer.valueOf(bean.getCompleteRate()), 2000);

                            }
                            if (StringUtils.isNotEmpty(jsonObj.getString("list"))) {
                                List<DeviceHouseDayPlanMappingEntity> jsonArray = new ArrayList<DeviceHouseDayPlanMappingEntity>(JSONArray.parseArray(jsonObj.getString("list"), DeviceHouseDayPlanMappingEntity.class));
                                listEasy.clear();
                                if (jsonArray.size() <= 6) {
                                    listEasy.addAll(jsonArray);
                                } else {
                                    listEasy.addAll(jsonArray.subList(0, 3));
                                    listEasy.addAll(2, jsonArray.subList(jsonArray.size() - 4, jsonArray.size() - 1));
                                }
                                adapterEasy.notifyDataSetChanged();


                            }
                        } else {
                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void getPlan() {
        OkHttpUtils
                .get(NewBaseUrl.get_plan_report)
                .headers("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("setDeviceConut", "获取简易车间汇总数据: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            if (StringUtils.isNotEmpty(jsonObj.getString("entity"))) {
                                DeviceHouseDayPlanEntity bean = (DeviceHouseDayPlanEntity) JSON.parseObject(jsonObj.getString("entity"), DeviceHouseDayPlanEntity.class);
                                Object[] str = new Object[]{bean.getCompleteRate() + "%", bean.getPlanOutput(), bean.getFinishCount(), bean.getReportOutput()};
                                ViewUtil.setText(str, tvPlanRate, tvPlanPlan, tvPlanReport, tvPlanCollect);
                                pbPlan.setCurProgress(Integer.valueOf(bean.getCompleteRate()), 2000);
                            }
                        } else {
                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void getTally() {
        OkHttpUtils
                .get(NewBaseUrl.get_tally_report)
                .headers("token", token)
                .params("companyId", companyId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("setDeviceConut", "获取点检汇总数据: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            if (StringUtils.isNotEmpty(jsonObj.getString("data"))) {
                                CompanyStaticsDataDto bean = (CompanyStaticsDataDto) JSON.parseObject(jsonObj.getString("data"), CompanyStaticsDataDto.class);
                                setPie(bean);
                                tvRepairCount.setText(bean.getDeviceRepairCount() + "");
                                tvCheckCount.setText(bean.getDeviceNeedVerifyRepairCount() + "");

                            }
                        } else {
                            ToastUtil.error(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void setPie(CompanyStaticsDataDto bean) {
        ArrayList<PieData> chartData = new ArrayList<PieData>();
        double sum = bean.getCheckRecordPassCount() + bean.getCheckRecordNotPassCount() + bean.getCheckRecordNoNeedCheckCount() + bean.getCheckRecordNotCheckCount();
        double passRate = 0, notPassRate = 0, notNeedRate = 0, notCheckRate = 0;
        if (sum != 0) {
            passRate = ((double) bean.getCheckRecordPassCount() / sum) * 100;
            notPassRate = ((double) bean.getCheckRecordNotPassCount() / sum) * 100;
            notNeedRate = ((double) bean.getCheckRecordNoNeedCheckCount() / sum) * 100;
            notCheckRate = ((double) bean.getCheckRecordNotCheckCount() / sum) * 100;
            passRate = (double) Math.round(passRate * 100) / 100;
            notPassRate = (double) Math.round(notPassRate * 100) / 100;
            notNeedRate = (double) Math.round(notNeedRate * 100) / 100;
            notCheckRate = 100 - (passRate - notPassRate - notNeedRate);
        }

        chartData.add(new PieData("closed", passRate + "%通过" + bean.getCheckRecordPassCount() + "台", passRate, Color.rgb(88, 183, 73)));
        chartData.add(new PieData("inspect", notPassRate + "%不通过" + bean.getCheckRecordNotPassCount() + "台", notPassRate, Color.rgb(200, 78, 63)));
        chartData.add(new PieData("open", notNeedRate + "%不点检" + bean.getCheckRecordNoNeedCheckCount() + "台", notNeedRate, Color.rgb(80, 127, 216)));
        chartData.add(new PieData("workdone", notCheckRate + "%未点检" + bean.getCheckRecordNotCheckCount() + "台", notCheckRate, Color.rgb(164, 164, 164), true));
        pcTally.initView(chartData);

    }

    private void setOee(CompanyBeltlineReportDto bean) {
        if (swDeviceRate.getSelectedTab() == 0) {
            wvOeeNow.setProgressValue(Double.valueOf(bean.getDayOee()).intValue());
            wvOeeAverage.setProgressValue(Double.valueOf(bean.getDayIndustryOee()).intValue());
            wvOeeTop.setProgressValue(Double.valueOf(bean.getDayMaxIndustryOee()).intValue());
            tvOeeNow.setText(bean.getDayOee() + "%");
            tvOeeAverage.setText(bean.getDayIndustryOee() + "%");
            tvOeeTop.setText(bean.getDayMaxIndustryOee() + "%");
            if (Double.valueOf(bean.getDayOee()) < Double.valueOf(bean.getDayIndustryOee())) {
                wvOeeNow.setWaveColor(getResources().getColor(R.color.wave_warn));
            } else {
                wvOeeNow.setWaveColor(getResources().getColor(R.color.wave_normal));

            }
        } else {
            wvOeeNow.setProgressValue(Double.valueOf(bean.getMonthOee()).intValue());
            wvOeeAverage.setProgressValue(Double.valueOf(bean.getMonthIndustryOee()).intValue());
            wvOeeTop.setProgressValue(Double.valueOf(bean.getMonthMaxIndustryOee()).intValue());
            tvOeeNow.setText(bean.getMonthOee() + "%");
            tvOeeAverage.setText(bean.getMonthIndustryOee() + "%");
            tvOeeTop.setText(bean.getMonthMaxIndustryOee() + "%");
            if (Double.valueOf(bean.getMonthOee()) < Double.valueOf(bean.getMonthIndustryOee())) {
                wvOeeNow.setWaveColor(getResources().getColor(R.color.wave_warn));
            } else {
                wvOeeNow.setWaveColor(getResources().getColor(R.color.wave_normal));
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getData();
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.button_blue), false);
        MobclickAgent.onPageStart("报表"); //统计页面，"MainScreen"为页面名称，可自定义

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("报表");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_easy_rank, R.id.tv_plan_rank})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_easy_rank:
                ViewUtil.hideReport(rlEasyRank, tvEasyRank);
                break;
            case R.id.tv_plan_rank:
                break;
        }
    }
}
